package com.zzy.bridge;

import com.zzy.RegisterLoginType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RegisterLoginComponentFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private static final Map<String, AbstractRegisterLoginComponent> cache = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        Map<String, Object> registerLoginComponentMap = applicationContext.getBeansWithAnnotation(RegisterLoginType.class);

        registerLoginComponentMap.forEach((beanName, bean) -> {
            if (bean instanceof RegisterLoginFuncInterface) {
                RegisterLoginType annotation = bean.getClass().getAnnotation(RegisterLoginType.class);
                if (annotation != null) {
                    String loginType = annotation.value();
                    cache.put(loginType, new RegisterLoginComponent((RegisterLoginFuncInterface) bean));
                }
            }
        });
    }

    public static AbstractRegisterLoginComponent getInstance(String type) {
        AbstractRegisterLoginComponent registerLoginComponent = cache.get(type);
        if(registerLoginComponent == null) {
            throw new UnsupportedOperationException("Invalid type!");
        }
        return registerLoginComponent;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
